import { Button, Input, Toast } from "antd-mobile";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { addPerson } from "../../store/persons/indexSlice";
import axios from "axios";

const AddDialog = ({ close }) => {
  const [name, setName] = useState("");
  const [code, setCode] = useState("");
  const dispatch = useDispatch();
  const handleOk = () => {
    if (name && code) {
      dispatch(
        addPerson({ name, code, id: Math.random().toString().slice(2) })
      );
      close();
    }
  };
  const saoMiao = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.click();

    input.onchange = () => {
      const file = input.files[0];
      if (file.type.includes("image")) {
        // 图像数据，base64编码后进行，需去掉编码头（data:image/jpeg;base64, ）
        // 要求base64编码和urlencode后大小不超过8M，最短边至少15px，最长边最大8192px，支持jpg/jpeg/png/bmp格式
        const fr = new FileReader();
        fr.readAsDataURL(file);
        fr.addEventListener("load", async () => {
          // base64编码
          console.log(fr.result);
          const result = (
            fr.result.replace("data:image/jpeg;base64,", "")
          );

          // 发送给百度
          const access_token = await getAccessToken();

          function getAccessToken() {
            let options = {
              method: "POST",
              url:
                "/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=" +
                "imsmA7O8WtX193NSfCdDolhp" +
                "&client_secret=" +
                "6Y9XEjQFGX81nv5ClpniD6ZbEDG2nOTS",
            };
            return new Promise((resolve, reject) => {
              axios(options)
                .then((res) => {
                  resolve(res.data.access_token);
                })
                .catch((error) => {
                  reject(error);
                });
            });
          }

          const resp = await axios.post(
            `/baidu/rest/2.0/ocr/v1/idcard?access_token=${access_token}`,
            {
              image: result,
              id_card_side: "front",
              detect_ps: false,
              detect_risk: false,
              detect_quality: false,
              detect_photo: false,
              detect_card: false,
              detect_direction: false,
            },
            {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            }
          );
          setName(resp.data.words_result['姓名'].words)
          setCode(resp.data.words_result['公民身份号码'].words)
        });
      } else {
        Toast.show("请上传图片");
      }
    };
  };

  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        backgroundColor: "rgba(0,0,0,0.7)",
        position: "fixed",
        left: 0,
        top: 0,
      }}
    >
      <div
        className="content"
        style={{
          position: "absolute",
          left: "50%",
          top: "50%",
          transform: "translate(-50%,-50%)",
          backgroundColor: "#fff",
          width: "80%",
          padding: 10,
        }}
      >
        <h2 className="title" style={{ textAlign: "center" }}>
          添加人员
        </h2>

        <Input
          placeholder="请输入姓名"
          style={{ margin: "10px 0" }}
          value={name}
          onChange={(e) => setName(e)}
        ></Input>
        <Input
          placeholder="请输入身份证"
          style={{ margin: "10px 0" }}
          value={code}
          onChange={(e) => setCode(e)}
        ></Input>
        <Button
          onClick={handleOk}
          block
          color="primary"
          style={{ margin: "10px 0" }}
        >
          确定
        </Button>
        <Button
          onClick={() => saoMiao()}
          block
          style={{ margin: "10px 0" }}
          color="danger"
        >
          扫描
        </Button>
        <Button onClick={close} block style={{ margin: "10px 0" }}>
          取消
        </Button>
      </div>
    </div>
  );
};

export default AddDialog;
